<?php
namespace App\Imports;
use App\Http\Util\HomeTool;
use App\Models\AllExam;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;

class Import{


    private function getEnValue($zhName)
    {
        $column = [
            '证件号码'=>'id_card',
            '真实姓名' => 'real_name',
            '证件类型' => 'card_type',
            '出生日期'=>'birth',
            '性别'=>'sex',
            '学历'=>'education',
            '联系地址'=>'address',
            '联系方式'=>'mobile',
            '工作单位'=>'employer',
            '工作年限'=>'work_years',
            '职业工种名称一'=>'work_first_name',
            '职业等级一'=>'work_first_level',
            '发证日期一'=>'work_first_date',
            '职业工种名称二'=>'work_second_name',
            '职业等级二'=>'work_second_level',
            '发证日期二'=>'work_second_date',
            '职业工种名称三'=>'work_third_name',
            '职业等级三'=>'work_third_level',
            '发证日期三'=>'work_third_date',
            '毕业院校'=>'finish_school',
            '毕业日期'=>'finish_date',
            '毕业专业'=>'finish_profession',
            '毕业编号'=>'finish_number',
            '专业技术职称'=>'technical_titles',
            '发证机构'=>'issuing_agency',
            '一寸照'=>'image',
            '证件照正面'=>'card_image_front',
            '证件照反面'=>'card_image_back',
            '附件信息'=>'image_urls',
            '考核类型'=>'exam_type'
        ];
        return $column[$zhName];
    }
    public function import($file,$examId, int $sheet = 0, int $columnCnt = 0)
    {
        //设置图片路径
        $folder_name = "upload/image/exam_".$examId.'/' . date("Ym/d", time());
        if (!is_dir($folder_name)){
            mkdir($folder_name, 0777,true);
        }
        try {
            $extension =$file->getClientOriginalExtension();
            if('csv' == $extension) {
                $objRead = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
            } else if('xls' == $extension) {
                $objRead = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
            } else {
                $objRead = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
            }
            $obj = $objRead->load($file);
            $currSheet = $obj->getSheet($sheet);
            if (0 == $columnCnt) {
                /* 取得最大的列号 */
                $columnH = $currSheet->getHighestColumn();
                /* 兼容原逻辑，循环时使用的是小于等于 */
                $columnCnt = Coordinate::columnIndexFromString($columnH);
            }
            /* 获取总行数 */
            $rowCnt = $currSheet->getHighestRow();
            $titlefiled   = [];//excel 字段
            for($i = 1; $i <= $columnCnt; $i ++) {
                $cellName = Coordinate::stringFromColumnIndex($i).'1';
                $cellVal = $currSheet->getCell($cellName)->getValue();
                $titlefiled[] = $this->getEnValue($cellVal);
            }
            for($i = 2; $i <= $rowCnt; $i++) {
                $row = [];
                for($j = 1; $j <= $columnCnt; $j++) {
                    $cellName = Coordinate::stringFromColumnIndex($j) . $i;
                    $cellVal = $currSheet->getCell($cellName)->getValue();
                    $key = $titlefiled[$j-1];
                    if($cellVal){
                        $row[$key] = $cellVal;
                    }
                }
                    if(count($row)>0){
                        $data[] = $row;
                    }
            }
            $temp = 0;//用于多张图片
            foreach ($currSheet->getDrawingCollection() as $drawing) {
                if ($drawing instanceof MemoryDrawing) {
                    ob_start();
                    call_user_func(
                        $drawing->getRenderingFunction(),
                        $drawing->getImageResource()
                    );
                    $imageContents = ob_get_contents();
                    ob_end_clean();
                    switch ($drawing->getMimeType()) {
                        case \PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
                            $extension = 'png';
                            break;
                        case \PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
                            $extension = 'gif';
                            break;
                        case \PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
                            $extension = 'jpg';
                            break;
                    }
                } else {
//                    echo '<pre>';
//                    print_r($drawing);
//                    echo '</pre>';
//                    exit;
                    $zipReader = fopen($drawing->getPath(), 'r');
                    $imageContents = '';
                    while (!feof($zipReader)) {
                        $imageContents .= fread($zipReader, 1024);
                    }
                    fclose($zipReader);
                    $extension = $drawing->getExtension();
                }
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                $startColumnindex = Coordinate::columnIndexFromString($startColumn) - 1;
                $myFileName = time() . '_' .uniqid() . '.' . $extension;
                if ($temp == $startColumnindex) {
                    $file = "{$file},";
                    $file .= "/{$folder_name}/{$myFileName}";
                    $data[$startRow - 2][$titlefiled[$startColumnindex]] = json_encode(explode(',', $file));
                } else {
                    $temp = $startColumnindex;
                    $file = "/{$folder_name}/{$myFileName}";
                    $data[$startRow - 2][$titlefiled[$startColumnindex]] = json_encode($file);
                }
                file_put_contents("{$folder_name}/{$myFileName}", $imageContents);
            }
//            foreach($data as $k => $v){
   //             $urls = json_decode($data[$k]['image_urls']);
//                $data[$k]['image_urls'] = HomeTool::makeZip($urls,$examId);
//            }
            return $data;
        }catch (\Exception $e) {
            throw $e;
        }
    }

}
